#include "DList.h"


DListNode* LTInit()
{
	//assert(head);
	//DListNode* head = (DListNode*)malloc(sizeof(DListNode));
	DLinkList phead = SetListNode(-1);
	phead->next = phead;
	phead->prev = phead;
	return phead;
}

void LTDestory(DLinkList phead)
{
	DListNode* p = phead->next;
	while (p != phead)
	{
		DListNode* q = p->next;
		free(p);
		p = q;
	}
	free(phead);
	//phead = NULL;

}

void LTPrint(DLinkList phead)
{
	assert(phead);

	printf("<=head=>");
	DListNode* p = phead->next;
	while (p!=phead)
	{
		printf("%d <=>", p->data);
		p = p->next;
	}
	printf("\n");
}

DListNode* SetListNode(LTDateType x)
{
	DListNode* newnode = (DListNode*)malloc(sizeof(DListNode));
	if (newnode == NULL)
	{
		perror("malloc error");
		return NULL;
	}
	newnode->data = x;
	newnode->next = NULL;
	newnode->prev = NULL;

	return newnode;
}

bool Empty(DLinkList phead)
{
	assert(phead);
	return phead->next == phead;
}

void LTPushBack(DLinkList phead, LTDateType x)
{
	assert(phead);

	/*DListNode* newnode = SetListNode(x);
	DListNode* tail = phead->prev;

	tail->next = newnode;
	newnode->prev = tail;
	newnode->next = phead;
	phead->prev = newnode;*/

	LTInsert(phead, x);

}


void LTPopBack(DLinkList phead)
{
	assert(phead);
	//assert(!Empty(phead));
	//DListNode* Delete = phead->prev;
	//DListNode* pre = Delete->prev;

	//pre->next = phead;
	//phead->prev = pre;

	//free(Delete);
	//Delete = NULL;

	LTErase(phead->prev);
}


void LTPushFront(DLinkList phead, LTDateType x)
{
	assert(phead);

	/*DListNode* newnode = SetListNode(x);
	DListNode* p = phead->next;
	newnode->next = p;
	p->prev = newnode;
	newnode->prev = phead;
	phead->next = newnode;*/

	LTInsert(phead->next, x);
	
}

void LTPopFront(DLinkList phead)
{
	assert(phead);
	assert(!Empty(phead));
	/*DListNode* p = phead->next;
	phead->next = p->next;
	p->next->prev = phead;
	free(p);
	p = NULL;*/

	LTErase(phead->next);
}

DListNode* ListFind(DListNode* phead, LTDateType x)
{
	assert(phead);
	DListNode* p = phead->next;
	while (p != phead)
	{
		if (p->data == x)
		{
			return p;
		}
		p = p->next;
	}
	return NULL;
}


void LTInsert(DListNode* pos, LTDateType x)
{
	assert(pos);
	DListNode* pre = pos->prev;
	DListNode* newnode = SetListNode(x);

	pre->next = newnode;
	newnode->prev = pre;

	newnode->next = pos;
	pos->prev = newnode;
}

void LTErase(DListNode* pos)
{
	assert(pos);
	DListNode* pre = pos->prev;
	DListNode* q = pos->next;

	pre->next = q;
	q->prev = pre;
	free(pos);
	//pos = NULL;
}